//get post put delete
function ajax(obj) {
    let str = "";
    for (let key in obj.params) {
      // str += key+"="+params[key]+"&";
      str += `${key}=${obj.params[key]}&`;
    }
//咱们要把结尾的&符号去掉
    str = str.replace(/&$/,"");

    let xhr = new XMLHttpRequest();
    if (obj.type == "get") {
      if (str) {
        xhr.open("get", obj.url + "?" + str);
      } else {
        xhr.open("get", obj.url);
      }
      // 如果需要这个请求头的话要满足的条件。
      if(obj.author){
        xhr.setRequestHeader(
          "authorization",
          localStorage.getItem("token")
        );
        }
      xhr.send();
    }
    if (obj.type == "post") {
      xhr.open("post", obj.url);
      xhr.setRequestHeader(
        "Content-type",
        "application/x-www-form-urlencoded"
      );

      // 如果需要设置验证。
      if(obj.author){
      xhr.setRequestHeader(
        "authorization",
        localStorage.getItem("token")
      );
      }
      
      xhr.send(str);
    }

    if(obj.type=="put"){
        xhr.open("put",obj.url);
        xhr.setRequestHeader(
            "Content-type",
            "application/x-www-form-urlencoded"
          );
          xhr.send(str);

    }

    if(obj.type=="delete"){
        xhr.open("delete",obj.url);
        xhr.send();
    }

    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          let data = xhr.responseText;
          obj.fn(data);
        }
      }
    };
  }